
package com.service.impl;


import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.mapper.TokenMapper;
import com.pojo.po.TokenPO;
import com.service.TokenService;
import com.utils.CommonUtil;
import com.utils.PageUtils;
import com.utils.Query;


/**
 * token
 */
@Service("tokenService")
public class TokenServiceImpl extends ServiceImpl<TokenMapper, TokenPO> implements TokenService {

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		Page<TokenPO> page = this.selectPage(
                new Query<TokenPO>(params).getPage(),
                new EntityWrapper<TokenPO>()
        );
        return new PageUtils(page);
	}

	@Override
	public List<TokenPO> selectListView(Wrapper<TokenPO> wrapper) {
		return baseMapper.selectListView(wrapper);
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params,
			Wrapper<TokenPO> wrapper) {
		 Page<TokenPO> page =new Query<TokenPO>(params).getPage();
	        page.setRecords(baseMapper.selectListView(page,wrapper));
	    	PageUtils pageUtil = new PageUtils(page);
	    	return pageUtil;
	}

	@Override
	public String generateToken(Long userid,String username, String tableName, String role) {
		TokenPO tokenPO = this.selectOne(new EntityWrapper<TokenPO>().eq("userid", userid).eq("role", role));
		String token = CommonUtil.getRandomString(32);
		Calendar cal = Calendar.getInstance();   
    	cal.setTime(new Date());   
    	cal.add(Calendar.HOUR_OF_DAY, 1);
		if(tokenPO !=null) {
			tokenPO.setToken(token);
			tokenPO.setExpiratedtime(cal.getTime());
			this.updateById(tokenPO);
		} else {
			this.insert(new TokenPO(userid,username, tableName, role, token, cal.getTime()));
		}
		return token;
	}

	@Override
	public TokenPO getTokenEntity(String token) {
		TokenPO tokenPO = this.selectOne(new EntityWrapper<TokenPO>().eq("token", token));
		if(tokenPO == null || tokenPO.getExpiratedtime().getTime()<new Date().getTime()) {
			return null;
		}
		return tokenPO;
	}
}
